package com.example.webshiro.shiro;

import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LuoYu
 * date 2021/2/3
 */
public class AuthFilter extends BasicHttpAuthenticationFilter {

    private Logger logger = LoggerFactory.getLogger(AuthFilter.class);



    private static final String requestId = "requestId";

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String remoteAddr = request.getRemoteAddr();
        logger.info("收到远程请求 ----> 请求来源地址:{} -- 请求id:{} -- 请求地址:{}",remoteAddr,httpServletRequest.getHeader(requestId),httpServletRequest.getServletPath());
        String origin = httpServletRequest.getHeader("Origin");
        if (origin == null || origin.isEmpty()) origin = "*";
        httpServletResponse.setHeader("Access-control-Allow-Origin", origin);
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        //true代表允许携带cookie
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        if(httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())){
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    @Override
    public void afterCompletion(ServletRequest request, ServletResponse response, Exception exception) throws Exception {
        super.afterCompletion(request, response, exception);
    }


    /**
     * 执行登录
     * @param request   请求
     * @param response  响应
     * @return           是否登录成功
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        logger.info("执行登录");
        JwtToken token = new JwtToken(this.getAuthzHeader(request));
        this.getSubject(request, response).login(token);
        return true;
    }


    /**
     * <p>是否允许访问</p>
     * @param request        请求
     * @param response       响应
     * @param mappedValue    映射之
     * @return               test
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //查看当前Header中是存在Header
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
         if (!this.isLoginAttempt(request, response)){
             logger.warn("远程主机:{}请求:{}未携带Token信息 ----> 拒绝访问",request.getRemoteAddr(),httpServletRequest.getServletPath());
             response401(response);
             return false;
         }
         try {
             executeLogin(request, response);
         }catch (Exception e){
             logger.error("请求未通过 ----> Error:{}",e.getMessage());
             response401(response);
         }
        return true;
    }

    /**
     * <p>尝试登录</p>
     * @param request   请求
     * @param response   响应
     * @return           是否可登录
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String header = this.getAuthzHeader(httpServletRequest);
        return header != null;
    }


    /**
     * <p>返回401</p>
     * @param response  响应
     */
    private void response401(ServletResponse response){
        HttpServletResponse servletResponse = WebUtils.toHttp(response);
        try {
            servletResponse.sendError(401,"Not Auth");
        }catch (IOException e){
            logger.error("触发401直接响应时发生错误 ----> 异常:{}",e.getMessage());
        }
    }



}


